<template>
  <div class="flexContent">
    <!-- 采购订单 -->
    <div class="searchBox">

      <el-form ref="form" :model="form" label-position="left" label-width="auto">
        <div class="serFlexBox">
          <div class="inputBox">
            <el-row :gutter="12" style="display: flex;flex-wrap: wrap;">
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="采购订单编号" prop="number">
                  <el-input v-clearEmoji v-model.trim="form.number" style="width: 95%" clearable placeholder="请输入采购订单编号"
                    @keyup.enter.native="searchList" />
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="收货仓库" prop="warehouseId">
                  <el-select @click.native="getWarehouseList" v-model="form.warehouseId" placeholder="请选择收货仓库"
                    style="width: 95%" filterable clearable popper-class="eloption">
                    <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="状态" prop="status">
                  <el-select v-model="form.status" placeholder="请选择状态" clearable style="width: 95%">
                    <el-option label="进行中" value="0" />
                    <el-option label="已收货" value="1" />
                    <el-option label="已作废" value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="供应商" prop="supplierId">
                  <el-select @click.native="getSupplierList" v-model="form.supplierId" placeholder="请选择供应商"
                    style="width: 95%" filterable clearable popper-class="eloption">
                    <el-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6" v-if="isAdmin">
                <el-form-item label="采购员" prop="userId">
                  <el-select @click.native="getBuyerList" v-model="form.userId" placeholder="请选择采购员" style="width: 95%"
                    filterable clearable popper-class="eloption">
                    <el-option v-for="item in buyerList" :key="item.id" :label="item.employeeName" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="btnBox">
            <el-button @click.stop="searchList" class="searchBtn" icon="el-icon-search">搜索</el-button>
            <el-button @click.stop="resetForm('form')" class="resetBtn" icon="el-icon-refresh-right">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <div class="add">
      <el-button class="addBtn" @click="toAddOrEditOrder('')" v-has="'procure_add'">新增</el-button>
    </div>
    <div class="table" id="tableBox" v-height>
      <div style="flex:1;">
        <vxe-table :column-config="{ resizable: true }" border class="tablebox" ref="xTable1"
          :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%" height="100%"
          size="medium" align="center">
          <vxe-column type="seq" title="序号" width="80" />
          <vxe-column field="number" title="采购订单编号" :min-width="elTableAdaptationWidth('number', tableData)" />
          <vxe-column field="supplierName" title="供应商名称" :min-width="elTableAdaptationWidth('supplierName', tableData)" />
          <vxe-column field="warehouseName" title="收货仓库"
            :min-width="elTableAdaptationWidth('warehouseName', tableData)" />
          <vxe-column field="totalPrice" title="订单总金额（元）" min-width="150">
            <template slot-scope="{ row }">
              {{ row.totalPrice | formatMoney }}
            </template>
          </vxe-column>
          <vxe-column field="expireDate" title="订单失效日期" min-width="150" />
          <vxe-column field="username" title="采购员" min-width="150" />
          <vxe-column field="commodityCount" title="状态" width="100">
            <template slot-scope="{ row }">
              <el-tag v-if="row.status === '0'" size="small">进行中</el-tag>
              <el-tag v-if="row.status === '1'" type="success" size="small">已收货</el-tag>
              <el-tag v-if="row.status === '2'" type="danger" size="small">已作废</el-tag>
            </template>
          </vxe-column>

          <vxe-column fixed="right" title="操作" width="200"
            v-if="$showFn(['procure_detail', 'procure_edit', 'procure_zf'])">
            <template slot-scope="{ row }">
              <el-button type="text" @click="toAddOrEditOrder(row, 1)" v-has="'procure_detail'">详情</el-button>
              <el-button v-if="row.status == '0'" type="text" @click="toAddOrEditOrder(row, 2)"
                v-has="'procure_edit'">修改</el-button>
              <el-button v-if="row.status == '0'" type="text" style="color: red" @click="toCancelOrder(row.id)"
                v-has="'procure_zf'">作废</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="paginationBox">
        <el-pagination :current-page.sync="page.pageNum" background :page-sizes="$pageSizes"
          :page-size.sync="page.pageSize" layout="total,->, sizes, prev, pager, next, jumper" :total="page.total"
          @size-change="changePageSize" @current-change="getBuyOrderList" />
      </div>

    </div>
  </div>
</template>

<script>
import { DecimalUtils } from "@/utils/math";
import {
  reqSupplierList,
  reqWarehouseList,
  reqBuyOrderList,
  reqBuyerList,
  reqCancelOrder,
} from "@/api/procure";
import { isAdmin } from "@/api/user";
export default {
  name: "ProcureOrder",
  data() {
    return {
      supplierList: [],
      warehouseList: [],
      buyerList: [],
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      form: {
        number: "",
        supplierId: "",
        warehouseId: "",
        userId: "",
        status: "",
      },
      tableData: [],
      isAdmin: false,
    };
  },
  filters: {
    formatMoney(val) {
      return DecimalUtils.subNumber(val, 2);
    }
  },
  mounted() {
    // this.getSupplierList();
    // this.getBuyerList();
    // this.getWarehouseList();
    this.getIsAdmin();
    this.getBuyOrderList();
  },
  methods: {
    // 是否是管理员
    async getIsAdmin() {
      const res = await isAdmin();
      if (res.code === 200) {
        console.log(res, "成功");
        this.isAdmin = res.data;
      }
      console.log(res);
    },
    // 获取供应商列表
    async getSupplierList() {
      const res = await reqSupplierList();
      if (res.code === 200) {
        this.supplierList = res.data.list;
      }
    },
    // 获取仓库列表
    async getWarehouseList() {
      const res = await reqWarehouseList();
      if (res.code === 200) {
        this.warehouseList = res.data;
      }
    },
    // 获取表格数据
    async getBuyOrderList() {
      const { pageNum, pageSize } = this.page;
      let { number, warehouseId, supplierId, userId, status } = this.form;
      if (!this.isSearch) {
        number = "";
        warehouseId = "";
        supplierId = "";
        userId = "";
        status = undefined;
      }
      const reqObj = {
        pageNum,
        pageSize,
        number,
        warehouseId,
        supplierId,
        userId,
        status,
      };
      const res = await reqBuyOrderList(reqObj);
      if (res.code === 200) {
        this.tableData = res.data.list;
        const $table = this.$refs.xTable1
        $table.loadData(this.tableData);
        this.page.total = res.data.total;
      }
    },
    // 获取采购员信息
    async getBuyerList() {
      const res = await reqBuyerList({ code: 0 });
      if (res.code === 200) {
        console.log(res);
        if (!res.data[0]) {
          return;
          // console.log(res.data[0].id, 'id')
        }
        console.log(res.data, "数组");
        this.buyerList = res.data;
      }
    },
    // 作废
    toCancelOrder(id) {
      this.$confirm(`确定将该订单作废?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await reqCancelOrder({ id });
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "作废成功",
            });
            this.getBuyOrderList();
          }
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // })
        });
    },
    // 修改每页几条
    changePageSize() {
      this.page.pageNum = 1;
      this.getBuyOrderList();
    },
    // 搜索
    searchList() {
      this.page.pageNum = 1;
      this.isSearch = true;
      this.getBuyOrderList();
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.page.pageNum = 1;
      this.page.pageSize = 20;
      this.isSearch = false;
      this.getBuyOrderList();
    },
    toAddOrEditOrder(row, isDetail = 0) {
      const { id, warehouseId } = row;
      if (isDetail == 0) {
        this.$router.push({ path: "procureOrderAdd" });
      } else if (isDetail == 1) {
        this.$router.push({
          path: "procureOrderDetail",
          query: { id, isDetail, warehouseId },
        });
      } else {
        this.$router.push({
          path: "procureOrderEdit",
          query: { id, isDetail, warehouseId },
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
